package leeon.bbsbrower.actions;

import ipworks.IPWorksException;

import java.util.ArrayList;

import leeon.bbsbrower.models.MailObject;
import leeon.bbsbrower.util.HTMLUtil;
import leeon.bbsbrower.util.HTTPBean;

public class BBSMailAction {
	
	public static final String URL_NEW_MAIL = Config.SERVER_URL + Config.SERVER_CGI + "bbsnewmail";
	
	public static final String URL_ALL_MAIL = Config.SERVER_URL + Config.SERVER_CGI + "bbsmail";
	
	public static final String URL_SEND_MAIL = Config.SERVER_URL + Config.SERVER_CGI + "bbssndmail";
	
	/**
	 * 获取新信
	 * @return
	 * @throws IPWorksException 
	 */
	public static MailObject[] getNewMails() throws IPWorksException {

		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String content = http.get(URL_NEW_MAIL);
		content = HTMLUtil.findStr(content, "<table width=100% border=0  bgcolor=#ffffff>", "</table>");
		String[] rows = HTMLUtil.dealTableRows(content);
			
		ArrayList<MailObject> list = new ArrayList<MailObject>();
		if (rows.length > 1) {
			for (int i = 1; i < rows.length; i ++) {
				String[] cells = HTMLUtil.dealTableCells(rows[i]);
				String[] titles = dealMailTitle(cells[4]);
					
				MailObject mail = new MailObject(
					cells[0],
					cells[1],
					HTMLUtil.removeHtmlTag(cells[2]).trim(),
					cells[3],
					titles[1],
					titles[0]
				);
				list.add(mail);
			}
		}
		
		return list.toArray(new MailObject[0]);
	}
	
	/**
	 * 获取所有信,from是null则从最新的开始
	 * @return
	 * @throws IPWorksException 
	 */
	public static MailObject[] getAllMails(String from) throws IPWorksException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String content = http.get(URL_ALL_MAIL + (from==null?"":"?start="+from));
		content = HTMLUtil.findStr(content, "<table width=100%>", "</table>");
		String[] rows = HTMLUtil.dealTableRows(content);
			
		ArrayList<MailObject> list = new ArrayList<MailObject>();
		if (rows.length > 1) {
			for (int i = 1; i < rows.length; i ++) {
				String[] cells = HTMLUtil.dealTableCells(rows[i]);
				String[] titles = dealMailTitle(cells[5]);
					
				MailObject mail = new MailObject(
					cells[0],
					cells[2],
					HTMLUtil.removeHtmlTag(cells[3]).trim(),
					cells[4],
					titles[1],
					titles[0]
				);
				list.add(mail);
			}
		}
			
		return list.toArray(new MailObject[0]);
	}
	
	
	/**
	 * 从信件标题html中，分解出标题以及url
	 * @param source
	 * @return
	 */
	private static String[] dealMailTitle(String source) {
		if (source != null) {
			int s = 0, e = 0;
			String[] re = new String[2];
			s = source.indexOf("<a href=");
			
			if (s != -1) s += 8;
			else return null;
			
			//url
			e = source.indexOf(">", s);
			if (e != -1) re[0] = source.substring(s, e);
			else return null;
			
			//title
			s = e + 1;
			e = source.indexOf("</a>", s);
			if (e != -1) re[1] = source.substring(s, e);
			else return null;
			
			//处理title
			if (re[1].startsWith("★")) 
				re[1] = "★  " + re[1].substring(1).trim();
			else
				re[1] = re[1].trim();
			
			re[0] = Config.SERVER_URL + Config.SERVER_CGI + re[0];
			
			return re;
		} else
			return null;
	}

	
	/**
	 * 通过信件对象中的地址,获取信件内容
	 * @param url
	 * @return
	 * @throws IPWorksException 
	 */
	public static String getMailContentByURL(String url) throws IPWorksException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String content = http.get(url);
		content = HTMLUtil.findStr(content, "<pre class=ansi>", "</pre>");
			
		if (content != null && content.length() != 0) {
			content = HTMLUtil.removeHtmlTag(content);
			content = HTMLUtil.dealImageTag(content);
			return content;
		} else {
			return "信件不存在"; 
		}
	}
	
	/**
	 * 发送信件，返回发送结果
	 * @return
	 * @throws ContentException 
	 * @throws IPWorksException 
	 */
	public static void sendMail(String id, String title, String sign, String text, boolean backup) throws ContentException, IPWorksException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String url = URL_SEND_MAIL + "?";
		url += "title=" + title + "&";
		url += "userid=" + id + "&";
		
		text = text.replaceAll("\n", "%0A").replaceAll("\r", "%0D");
		url += "text=" + text + "&";
			
		if (sign != null)
			url += "signature=" + sign + "&";
		else
			url += "signature=1&";
			
		if (backup) url += "backup=on";
			
		String content = http.get(url);
		if (content == null || content.indexOf("信件已寄给") == -1)
			throw new ContentException(content);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

}
